//
//  AIGirlChangeAiGirlViewController.swift
//  AIGirl
//
//  Created by Rae on 2024/1/22.
//

import UIKit

class AIGirlChangeAiGirlViewController: AIGirlBaseViewController {

    private lazy var backView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private lazy var backButton = c_make_ex(UIButton.self)
        .image("AIGirl_Signin_back").end()
    private lazy var rightButton = c_make_ex(UIButton.self)
        .end()
    private lazy var rightImageView = c_make_ex(UIImageView.self)
        .image("AIGirl_Message_setting_right").end()
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white).font(19.font_bold).alignment(.center)
        .text("Change avatar").end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    private lazy var nextButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(21.font_bold).corner(20.Scale)
        .text("Done").end()
    
    private var imgStr: String = ""
    var dataList:[AIGirlItemModel] = []
    private var girlId = 0
    private var modelId = 0
    
    var discoverClosure: (() -> Void)?
    var doneClosure: (() -> Void)?
    
    init() {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            backView
            backButton
            rightImageView
            rightButton
            titleLabel
            collectionView
            nextButton
        }
        
        backView.fillContainer()
        backButton.leading(15).top(.statusHeight).size(30)
        titleLabel.leading(15).trailing(15)
        titleLabel.CenterY == backButton.CenterY
        rightImageView.trailing(15)
        rightImageView.CenterY == backButton.CenterY
        rightButton.trailing(15).width(35).height(40)
        rightButton.CenterY == backButton.CenterY
        nextButton.leading(35.Scale).trailing(35.Scale).height(50.Scale).bottom(60)
        collectionView.leading(0).trailing(0).height(45)
        collectionView.Bottom == nextButton.Top - 35

        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.itemSize = CGSize(width: 40.0, height: 45.0)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 37.5, bottom: 0, right: 0)
        layout.scrollDirection = .horizontal
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlUserInfoChooseItem.self, forCellWithReuseIdentifier: AIGirlUserInfoChooseItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
//        rightImageView.layer.shouldRasterize = true
//        rightImageView.layer.rasterizationScale = UIScreen.main.scale
        DispatchQueue.main.async {
            self.startScalingAnimation()
        }
        backButton.addTarget(self, action: #selector(clickDismissButton), for: .touchUpInside)
        nextButton.addTarget(self, action: #selector(clickNextButton), for: .touchUpInside)
        rightButton.addTarget(self, action: #selector(clickRightButton), for: .touchUpInside)
    }
    
    private func startScalingAnimation() {
        let animationDuration = 0.5
        let scaleUp: CGFloat = 1.3

        // 放大和缩小动画
        let scaleUpAnimation = CABasicAnimation(keyPath: "transform.scale")
        scaleUpAnimation.toValue = NSNumber(value: Float(scaleUp))
        scaleUpAnimation.duration = animationDuration
        scaleUpAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

        // 创建缩小动画
        let scaleDownAnimation = CABasicAnimation(keyPath: "transform.scale")
        scaleDownAnimation.toValue = NSNumber(value: Float(1.0))
        scaleDownAnimation.duration = animationDuration
        scaleDownAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

        // 创建动画组
        let animationGroup = CAAnimationGroup()
        animationGroup.animations = [scaleUpAnimation, scaleDownAnimation]
        animationGroup.duration = animationDuration * 2 // 放大 + 缩小
        animationGroup.repeatCount = .infinity

        // 将动画应用到图像视图的 layer 上
        rightImageView.layer.add(animationGroup, forKey: "scaleAnimation")
    }
    
    private func loadData(){
        
        self.request.start(.girlList(num: 1, size: 100, startIndex: 0, type: 0), type: AIGirlListModel.self) { result in
            
            if result.isSuccessful, let model = result.model {
                var dataSource = [AIGirlItemModel]()
                dataSource = model.rows
//                var index = 0
                let modelId = UserDefaultsManager.getInt(forKey: .modelId)
                for var itemM in dataSource {
//                    index += 1
                    if itemM.modelId == modelId {
                        self.imgStr = itemM.image
                        self.backView.loadImage(url: itemM.image)
                        self.girlId = itemM.girlId
                        self.modelId = itemM.modelId
                        itemM.isSel = true
                    }else {
                        itemM.isSel = false
                    }
                    
                    self.dataList.append(itemM)
                }
                self.collectionView.reloadData()
            }
        }

    }
    
    @objc private func clickNextButton(){
        
        if girlId != 0 && modelId != 0 {
            
            request.start(.saveMyGirl(girlId: girlId, modelId: modelId)) { result in
                if result.isSuccessful {
                    UserDefaultsManager.setInt(self.girlId, forKey: .girlId)
                    UserDefaultsManager.setInt(self.modelId, forKey: .modelId)
                    UserDefaultsManager.setString(self.imgStr, forKey: .girlAvatar)
                    self.updateBgView()
                    self.dismiss(animated: true){
                        self.doneClosure?()
                    }
                }
            }
        }
    }
    
    private func updateBgView(){
        
        if girlId != 0 && modelId != 0 {
            request.start(.saveChatBackground(girlId: girlId, photoId: modelId)) { _ in
                
            }
        }        
    }
    
    @objc private func clickRightButton(){
        
        self.dismiss(animated: true){
            self.discoverClosure?()
        }        
    }
    
    @objc private func clickDismissButton(){
        self.dismiss(animated: true)
    }
}

extension AIGirlChangeAiGirlViewController: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlUserInfoChooseItem.description(), for: indexPath) as? AIGirlUserInfoChooseItem else { return UICollectionViewCell() }
        item.model = dataList[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [AIGirlItemModel]()
        dataList.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        self.imgStr = models[indexPath.row].image
        self.backView.loadImage(url: models[indexPath.row].image)
        self.girlId = models[indexPath.row].girlId
        self.modelId = models[indexPath.row].modelId
        dataList = models
        collectionView.reloadData()
    }
}
